<!--
Date: 2025-08-13
Copyright (c) 2025 Industrial Software Feature Database
-->
<template>
  <div v-loading="loading" class="p-2" element-loading-text="转换中...请等待！">
    <el-card shadow="hover">
      <template #header>
        <div class="card-header">
          <span>CAX数据转换</span>
        </div>
      </template>
      <el-radio-group v-model="conversionForm.convertType" class="mb-[10px]" @change="handleRadioChange">
        <el-radio-button v-for="(item, index) in caxConvertInfos" :key="'radio' + index" :label="item.label" :value="item.label" />
      </el-radio-group>
      <el-form ref="conversionFormRef" :model="conversionForm" label-width="100px" :rules="rules">
        <el-form-item label="输入模型：" prop="inputType">
          <el-radio-group v-model="conversionForm.inputType" @change="handleInputModelChange">
            <el-radio v-for="(item, index) in inputModelTypes" :key="'radio-item-input' + index + conversionForm.convertType" :value="item.label">{{
              item.label
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="输出模型：" prop="outputType">
          <el-radio-group v-model="conversionForm.outputType">
            <el-radio v-for="(item, index) in outputModelTypes" :key="'radio-item+output' + index + conversionForm.convertType" :value="item.label">{{
              item.label
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="选择模型：" prop="file">
          <el-upload
            ref="conversionUploadRef"
            style="width: 80%"
            :accept="fileType"
            action=""
            :auto-upload="false"
            :before-upload="handleBefore"
            :on-remove="handleRemove"
            :on-exceed="handleExceed"
            :on-change="handleChange"
          >
            <el-button type="primary">点击上传</el-button>
            <template v-if="fileType" #tip>
              <div class="el-upload__tip">只能上传{{ fileType }}文件</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" :loading="loading" @click="handleConvert">开始转换</el-button>
        <el-button :disabled="convertData?.status !== '1'" type="primary" :loading="loading" @click="handleTargetDownload">下载转换文件</el-button>
      </template>
    </el-card>
    <!-- <el-dialog v-model="dialogVisible" title="提示" width="500" :before-close="handleClose">
      <el-result icon="success" title="转换成功" sub-title="Please follow the instructions"></el-result>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleClose"> 关闭 </el-button>
        </div>
      </template>
    </el-dialog> -->
  </div>
</template>

<script setup name="caxConversionPlatform" lang="ts">
import { optionType, caxConvertInfoForm, caxConvertInfoVO } from '@/api/caxConversionPlatform/type';
import type { UploadProps, FormRules } from 'element-plus';
import { caxConvertInfo, downloadCaxTarget } from '@/api/caxConversionPlatform/index';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const conversionFormRef = ref<ElFormInstance>();
const conversionUploadRef = ref<ElUploadInstance>();
const conversionForm = ref<caxConvertInfoForm>({
  convertType: 'CAD',
  inputType: undefined,
  outputType: undefined,
  file: undefined
});
const cadInputModelTypes: Array<optionType> = [
  {
    value: 'step',
    label: 'STEP'
  },
  {
    value: 'iges',
    label: 'IGES'
  },
  {
    value: 'parasolid',
    label: 'parasolid'
  },
  {
    value: 'CATPart',
    label: 'CATPart'
  },
  {
    value: 'CATProduct',
    label: 'CATProduct'
  },
  {
    value: 'sldprt',
    label: 'sldprt'
  },
  {
    value: 'sldasm',
    label: 'sldasm'
  },
  {
    value: 'dwg',
    label: 'DWG'
  },
  {
    value: 'dxf',
    label: 'DXF'
  }
];
const cadOutputModelTypes: Array<optionType> = [
  {
    value: 'step',
    label: 'STEP'
  },
  {
    value: 'iges',
    label: 'IGES'
  },
  {
    value: 'parasolid',
    label: 'parasolid'
  },
  {
    value: 'stl',
    label: 'STL'
  },
  {
    value: 'obj',
    label: 'OBJ'
  },
  {
    value: 'CATPart',
    label: 'CATPart'
  },
  {
    value: 'CATProduct',
    label: 'CATProduct'
  },
  {
    value: 'sldprt',
    label: 'sldprt'
  },
  {
    value: 'sldasm',
    label: 'sldasm'
  },
  {
    value: 'dwg',
    label: 'DWG'
  },
  {
    value: 'dxf',
    label: 'DXF'
  }
];
const caeInputModelTypes: Array<optionType> = [
  {
    value: 'bdf',
    label: 'BDF'
  },
  {
    value: 'inp',
    label: 'INP'
  },
  {
    value: 'cdb',
    label: 'CDB'
  }
];
const caeOutputModelTypes: Array<optionType> = [
  {
    value: 'bdf',
    label: 'BDF'
  },
  {
    value: 'inp',
    label: 'INP'
  },
  {
    value: 'cdb',
    label: 'CDB'
  },
  {
    value: 'vtk',
    label: 'VTK'
  },
  {
    value: 'msh',
    label: 'MSH'
  }
];
const caeInputModelTypes2: Array<optionType> = [
  {
    value: 'op2',
    label: 'OP2'
  },
  {
    value: 'odb',
    label: 'ODB'
  },
  {
    value: 'rst',
    label: 'RST'
  },
  {
    value: 'h5',
    label: 'H5'
  }
];
const caeOutputModelTypes2: Array<optionType> = [
  {
    value: 'vtk',
    label: 'VTK'
  },
  {
    value: 'h5',
    label: 'H5'
  }
];
const convertData = ref<caxConvertInfoVO>();
const inputModelTypes = ref<Array<optionType>>(cadInputModelTypes);
const outputModelTypes = ref<Array<optionType>>(cadOutputModelTypes);
const caxConvertInfos = ref<Array<any>>([
  {
    value: 'CAD',
    label: 'CAD',
    inputModelTypes: cadInputModelTypes,
    outputModelTypes: cadOutputModelTypes,
    effectiveTypes: [
      {
        input: 'STEP',
        output: 'OBJ'
      }
    ]
  },
  {
    value: 'CAE1',
    label: 'CAE输入文件',
    inputModelTypes: caeInputModelTypes,
    outputModelTypes: caeOutputModelTypes,
    effectiveTypes: [
      {
        input: 'BDF',
        output: 'INP'
      }
    ]
  },
  {
    value: 'CAE2',
    label: 'CAE输出文件',
    inputModelTypes: caeInputModelTypes2,
    outputModelTypes: caeOutputModelTypes2,
    effectiveTypes: [
      {
        input: 'OP2',
        output: 'VTK'
      }
    ]
  }
]);
const fileType = ref('');
const loading = ref(false);
const dialogVisible = ref(false);
const rules = reactive<FormRules<caxConvertInfoForm>>({
  convertType: [{ required: true, message: '请选择转换类型', trigger: 'change' }],
  inputType: [{ required: true, message: '请选择输入模型', trigger: 'change' }],
  outputType: [{ required: true, message: '请选择输出模型', trigger: 'change' }],
  file: [{ required: true, message: '请选择文件', trigger: 'change' }]
});
const handleRadioChange = (value: string | number | boolean) => {
  const obj = caxConvertInfos.value.find((item) => item.label === value);
  if (obj) {
    inputModelTypes.value = obj.inputModelTypes;
    outputModelTypes.value = obj.outputModelTypes;
  }
  fileType.value = '';
  conversionForm.value.inputType = null;
  conversionForm.value.outputType = null;
  conversionFormRef.value.resetFields();
  conversionUploadRef.value.clearFiles();
};
const handleInputModelChange = (value: string) => {
  const str = inputModelTypes.value.find((item) => item.label === value);
  fileType.value = '.' + str.value;
};

// 文件上传函数
const handleRemove: UploadProps['onRemove'] = (file, uploadFiles) => {
  conversionForm.value.file = null;
  conversionFormRef.value.validateField(['file']);
};
// 数据文件
const handleBefore: UploadProps['beforeUpload'] = (file) => {
  // let limit100M = file.size / 100 / 1024 / 1024 >= 1;
  // if (limit100M) {
  //     proxy?.$modal.msgError("单个文件大小应该小于100M！")
  //     return false
  // }
  const arr = file.name.split('.');
  const type = '.' + arr[arr.length - 1];
  const types = fileType.value.split(',');
  if (fileType.value && !types.includes(type)) {
    proxy?.$modal.msgError('请上传' + fileType.value + '文件！');
    return false;
  }
  return true;
};
const handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
  proxy?.$modal.msgWarning(`当前限制选择1个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + uploadFiles.length} 个文件！`);
};
const handleChange: UploadProps['onChange'] = (file: any, uploadFiles) => {
  const flag = handleBefore(file);
  if (!flag) {
    return false;
  }
  if (file.status === 'ready') {
    conversionForm.value.file = file.raw;
    conversionFormRef.value.validateField(['file']);
  }
};
const handleConvert = async () => {
  await conversionFormRef.value.validate((valid) => {
    if (valid) {
      loading.value = true;
      if (!checkType()) {
        proxy?.$modal.msgWarning('暂不支持此类型转换，该转换类型开发中');
        loading.value = false;
      } else {
        const formData = new FormData();
        formData.append('convertType', conversionForm.value.convertType === 'CAD' ? 'CAD' : 'CAE');
        formData.append('inputType', conversionForm.value.inputType);
        formData.append('outputType', conversionForm.value.outputType);
        formData.append('file', conversionForm.value.file);
        caxConvertInfo(formData)
          .then((res) => {
            convertData.value = res.data;
            if (convertData.value.status === '1') {
              proxy?.$modal.msgSuccess('转换成功！');
              loading.value = false;
            } else if (convertData.value.status === '2') {
              proxy?.$modal.msgError('转换失败！');
              loading.value = false;
            } else {
              proxy?.$modal.msg('转换中...');
            }
          })
          .catch(() => {
            loading.value = false;
          });
      }
    } else {
      proxy?.$modal.msgWarning('请完成表单！');
    }
  });
};
const checkType = () => {
  const obj = caxConvertInfos.value.find((item) => item.label === conversionForm.value.convertType);
  if (obj) {
    const index = obj.effectiveTypes.findIndex(
      (item) => item.input === conversionForm.value.inputType && item.output === conversionForm.value.outputType
    );
    if (index > -1) {
      return true;
    }
  }
  return false;
};
const downloadFile = (res, fileName) => {
  const blob = new Blob([res]);
  const objUrl = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.setAttribute('href', objUrl);
  link.setAttribute('download', fileName);
  link.style.display = 'none';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};
/** 导出按钮操作 */
const handleTargetDownload = () => {
  const row = convertData.value;
  downloadCaxTarget(row.id).then((res) => {
    const obj = outputModelTypes.value.find((item) => item.label === row.outputType);
    const fileName = row.sourceFileName.substring(0, row.sourceFileName.lastIndexOf('.')) + '.' + obj.value;
    downloadFile(res, fileName);
  });
};
const handleClose = () => {
  dialogVisible.value = false;
};
</script>
<style lang="scss" scoped>
:deep(.el-card__footer) {
  text-align: center;
}
</style>
